package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient  client;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper sensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    //@Async
    public void autoScanWmNews(Integer id) throws Exception {
        //1.通过id查询文章数据
        WmNews wmNews = wmNewsMapper.selectById(id);
        //2.判断文章数据是否存在,不存在则抛出异常
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }


        //3.完成机器审核的判断  1
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //3.1 抽取文章中的文本数据和图片数据-Map
            Map<String,Object> data = handleTextAndImages(wmNews);

            //敏感词审核
            boolean isSensitive = handleSensitiveScan(data.get("textContext").toString() ,wmNews);
            if (!isSensitive) {
                return;
            }

            //3.2 发送文本数据到阿里云进行审核 如果不通过则更新文章的审核状态和原
            boolean isTextScan = handleTextScan(data.get("textContext").toString() , wmNews);
            if (!isTextScan) {
                return;
            }
            //3.3 下载所有图片数据 进行审核  不通过则更新审核状态和原因
            boolean isImageScan =  handleImageScan((List<String>) data.get("images"),wmNews);
            if(!isImageScan)return;
            //3.4 调用Feign请求完成数据同步
            ResponseResult responseResult = saveAppArticle(wmNews);
            //3.5 更新文章的状态 和app_article表中的id到自媒体文章的表中
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }

            wmNews.setArticleId(Long.parseLong(responseResult.getData().toString()));
            updateWmNewStatus(wmNews,(short) 9,"审核成功");
        }



    }

    /**
     * 审核敏感词
     * @param textContent
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String textContent, WmNews wmNews) {
        boolean flag = true;
        //查询所有敏感词
        List<WmSensitive> wmSensitives = sensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> collect = wmSensitives.stream().map(item -> item.getSensitives()).collect(Collectors.toList());
        //初始化DFA的最大的Map
        SensitiveWordUtil.initMap(collect);
        //使用DFA校验
        Map<String, Integer> map = SensitiveWordUtil.matchWords(textContent);
        if (null != map && map.size() >0) {
            flag = false;
            updateWmNewStatus(wmNews,(short) 2,"文章中包含敏感词" + map);
        }
        //返回验证结果

        return flag;
    }

    /**
     * 数据同步-Feign请求来同步数据
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();

        BeanUtils.copyProperties(wmNews ,dto);

        dto.setLayout(wmNews.getType());
        dto.setCreatedTime(new Date());
        dto.setCollection(0);
        dto.setComment(0);
        dto.setViews(0);
        dto.setLikes(0);
        //查询作者相关的信息
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        dto.setAuthorId((long)wmNews.getUserId());
        if (wmNews != null) {
            dto.setAuthorName(wmUser.getName());
        }
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
       /* ArticleDtoBuilder articleDtoBuilder = new ArticleDtoBuilder(wmNews,  wmChannelMapper,wmUserMapper);
        articleDtoBuilder
                .buildBeanCopy()
                .buildBasic()
                .buildAuth()
                .buildChannel()
                .builder();*/


        ResponseResult responseResult = client.saveArticle(dto);
        return responseResult;

    }

    /**
     * 审核图片
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        boolean flag = true;
        if (null == images || images.size() == 0) {
            return flag;
        }
        //去重
        images = images.stream().distinct().collect(Collectors.toList());
        //minio下载图片
        List<byte[]> imagesList =new ArrayList<>(images.size());
        for (String imageUrl : images) {
            byte[] bytes = fileStorageService.downLoadFile(imageUrl);

            //图片的文字识别  和  自定义敏感词审核
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            BufferedImage read = ImageIO.read(in);
            String text = tess4jClient.doOCR(read);
            boolean isSensitive = handleSensitiveScan(text, wmNews);
            if(!isSensitive){
                flag = false;
                return flag;
            }

            imagesList.add(bytes);
        }
        //审核 解析
        Map map = greenImageScan.imageScan(imagesList);
        flag = parseScanResponse(wmNews, flag, map);


        return flag;
    }

    /**
     * 审核失败返回内容
     */
    private boolean parseScanResponse(WmNews wmNews, boolean flag, Map map) {
        if (null != map) {
            //审核失败
            if ("block".equals(map.get("suggestion"))) {
                updateWmNewStatus(wmNews, (short) 2, "文章中存在违规内容");
                flag = false;
            } else if ("review".equals(map.get("suggestion"))) {
                updateWmNewStatus(wmNews, (short) 3, "文章中存在不确定因数,转人工审核");
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 审核文本
     * @param textContext
     * @return
     */
    private boolean handleTextScan(String textContext,WmNews wmNews) throws Exception {
        boolean flag = true;
        Map map = greenTextScan.greeTextScan(textContext);
        flag = parseScanResponse(wmNews, flag, map);
        return flag;
    }

    /**
     * 更新文章审核状态和原因
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNewStatus(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 3.1 抽取文本和图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //保存文本数据
        StringBuffer sb = new StringBuffer();
        //保存图片数据
        List<String> images = new ArrayList<>();

        if (StringUtils.isNotEmpty(wmNews.getContent())) {
            List<Map> list = JSON.parseArray(wmNews.getContent(), Map.class);

            for (Map map : list) {
                if ("image".equals(map.get("type"))) {
                    images.add(map.get("value").toString());
                } else if ("text".equals(map.get("type"))) {
                    sb.append(map.get("value").toString());
                }
            }
        }

        //sb中添加标题
        sb.append(wmNews.getTitle());
        //images中添加封面图片
        if (StringUtils.isNotEmpty(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String,Object> map = new HashMap<>();
        map.put("textContext", sb.toString());
        map.put("images",images);
        return map;
    }
}
